<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>AI Chat Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            background: #ffffff;
            width: 100vw;
            overflow: hidden;
            font-family: 'SF Pro Text', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Helvetica Neue', sans-serif;
        }

        body {
            height: 100vh;
            width: 100vw;
        }

        .main-container {
            width: 100vw;
            height: 100vh;
            display: flex;
            flex-direction: row;
            background: #ffffff;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 260px;
            min-width: 260px;
            background: #f7f7f8;
            border-right: 1px solid #e5e5e5;
            display: flex;
            flex-direction: column;
            height: 100vh;
            box-sizing: border-box;
            overflow: hidden;
            position: relative;
        }

        .sidebar-header {
            padding: 16px 16px 12px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e5e5e5;
            margin-bottom: 10px;
        }

        .sidebar-title {
            font-size: 1.05em;
            font-weight: 600;
            color: #202123;
        }

        .clear-all-btn {
            background: none;
            border: none;
            cursor: pointer;
            color: #6e6e80;
            font-size: 0.85em;
            padding: 6px 8px;
            border-radius: 4px;
            transition: background 0.15s;
        }

        .clear-all-btn:hover {
            background: #e5e5e6;
            color: #202123;
        }

        .session-list {
            flex: 1 1 auto;
            overflow-y: auto;
            padding: 0 8px 12px 8px;
        }

        /* 添加这个样式，当session-list里面有empty-sessions类时隐藏滚动条 */
        .session-list:has(.empty-sessions) {
            overflow-y: hidden;
        }

        .empty-sessions {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #8e8ea0;
            font-size: 0.9em;
            text-align: center;
            padding: 20px;
            overflow: hidden; /* 添加这行 */
        }

        .session-list button {
            display: flex;
            align-items: center;
            background: transparent;
            border: none;
            border-radius: 6px;
            font-size: 0.95em;
            font-weight: 500;
            color: #202123;
            cursor: pointer;
            transition: background 0.16s;
            margin: 0 0 4px 0;
            padding: 8px 12px; /* 减小内边距 */
            width: 100%;
            box-sizing: border-box;
        }

        .session-list button span {
            flex: 1;
            padding-right: 8px; /* 给删除按钮留出一些空间 */
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            text-align: left;
        }

        .session-list button.active, .session-list button:hover {
            background: #e5e5e6;
        }

        .session-delete {
            width: 24px !important; /* 强制宽度 */
            height: 24px !important; /* 强制高度 */
            min-width: 24px !important; /* 确保最小宽度 */
            padding: 0 !important; /* 移除内边距 */
            margin: 0 !important; /* 移除外边距 */
            opacity: 0;
            color: #6e6e80;
            background: none;
            border: none;
            font-size: 14px;
            cursor: pointer;
            border-radius: 4px;
            transition: opacity 0.2s, background 0.15s;
            display: flex !important;
            align-items: center;
            justify-content: center;
            margin-left: auto !important;
        }

        .session-list button:hover .session-delete {
            opacity: 1;
        }

        .session-delete:hover {
            background: #d1d1d2;
            color: #202123;
        }

        .sidebar .new-session {
            margin: 12px 8px 16px 8px;
            width: calc(100% - 16px);
            border-radius: 6px;
            background: #ffffff;
            border: 1px solid #e5e5e5;
            font-size: 0.95em;
            cursor: pointer;
            font-weight: 600;
            color: #202123;
            padding: 12px 0;
            transition: background 0.15s;
        }

        .sidebar .new-session:hover {
            background: #f0f0f0;
        }

        /* 聊天区域样式 */
        .chat-area {
            flex: 1 1 auto;
            display: flex;
            flex-direction: column;
            height: 100vh;
            background: #ffffff;
            box-sizing: border-box;
        }

        .chat-header {
            padding: 16px 40px 16px 40px;
            font-size: 1.15em;
            font-weight: 600;
            color: #202123;
            background: #ffffff;
            flex: 0 0 auto;
            border-bottom: 1px solid #e5e5e5;
        }

        .msg-list {
            flex: 1 1 auto;
            overflow-y: auto;
            padding: 30px 0 20px 0;
            background: #ffffff;
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            scroll-behavior: smooth;
        }

        .msg-list.empty {
            overflow-y: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .empty-chat-message {
            color: #8e8ea0;
            text-align: center;
            font-size: 1.1em;
            max-width: 450px;
            line-height: 1.6;
        }

        .msg-row {
            display: flex;
            margin-bottom: 20px;
            max-width: 800px;
            margin-left: auto;
            margin-right: auto;
            width: 100%;
        }

        .msg-row.user {
            justify-content: flex-end;
        }

        .msg-row.ai {
            justify-content: flex-start;
        }

        .msg-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            flex-shrink: 0;
        }

        .msg-avatar.user {
            background: #10a37f;
            color: white;
            margin-left: 12px;
        }

        .msg-avatar.ai {
            background: #6e6e80;
            color: white;
            margin-right: 12px;
        }

        .msg-content {
            max-width: calc(100% - 50px);
            display: flex;
            flex-direction: column;
        }

        .msg-bubble {
            padding: 16px 20px; /* 增加内边距 */
            font-size: 1em;
            line-height: 1.7;
            margin: 0;
            word-break: break-word;
            color: #353740;
            border-radius: 6px;
            overflow: hidden; /* 添加这行 */
        }

        .msg-bubble.user {
            background: #f7f7f8;
            color: #202123;
            text-align: right;
        }

        .msg-bubble.ai {
            background: #f7f7f8;
            color: #353740;
        }

        .msg-meta {
            font-size: 0.85em;
            color: #8e8ea0;
            margin: 4px 0 0 0;
        }

        .reasoning-container {
            position: relative;
            margin: 6px 0 10px 0;
            border-radius: 6px;
            overflow: hidden;
            border: 1px solid #e5e5e5;
        }

        .reasoning-header {
            padding: 8px 12px;
            background-color: #f7f7f8;
            font-size: 0.85em;
            color: #6e6e80;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
        }

        .reasoning-content {
            padding: 12px 16px;
            background: #f7f7f8;
            color: #444654;
            font-size: 0.95em;
            overflow: hidden;
            transition: max-height 0.3s, padding 0.3s;
            max-height: 1000px;
            white-space: pre-wrap;
            word-break: break-word;
        }

        .reasoning-container.collapsed .reasoning-content {
            max-height: 0;
            padding-top: 0;
            padding-bottom: 0;
        }

        .ai-reply-content {
            width: 100%;
            display: block;
        }

        /* 输入区域样式 */
        .chat-input-area {
            background: #ffffff;
            border-top: 1px solid #e5e5e5;
            padding: 16px 40px 24px 40px;
            z-index: 10;
            position: relative;
            max-width: 800px;
            margin: 0 auto;
            width: 100%;
        }

        .chat-input-area form {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        #preset-select, #preset-custom, #message {
            font-size: 1rem;
            width: 100%;
            box-sizing: border-box;
            border-radius: 6px;
            border: 1px solid #ccc;
            padding: 8px 12px;
        }

        #preset-select {
            height: 42px;
            background: #fff;
        }

        #preset-custom, #message {
            min-height: 50px;
            resize: vertical;
            font-family: inherit;
        }

        #message {
            border-radius: 12px;
            padding: 12px 16px;
            box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
            line-height: 1.4;
        }

        #message:focus {
            outline: none;
            box-shadow: 0 0 0 1px #10a37f;
        }

        .chat-input-row {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 4px;
            justify-content: space-between;
        }

        .chat-options {
            display: flex;
            align-items: center;
        }

        .chat-input-row label {
            margin: 0;
            font-weight: normal;
            font-size: 0.95em;
            color: #6e6e80;
            display: flex;
            align-items: center;
        }

        button[type="submit"] {
            padding: 8px 16px;
            border-radius: 6px;
            border: none;
            background: #10a37f;
            font-size: 0.95em;
            cursor: pointer;
            font-weight: 600;
            color: #ffffff;
            transition: background 0.15s;
        }

        button[type="submit"]:hover {
            background: #0e916f;
        }

        button[type="submit"]:disabled {
            background: #93c8bd;
            cursor: not-allowed;
        }

        /* 响应式布局 */
        @media (max-width: 900px) {
            .main-container {
                flex-direction: column;
            }

            .sidebar {
                width: 100vw;
                min-width: 0;
                max-height: 60px;
                height: 60px;
                flex-direction: row;
                border-right: none;
                border-bottom: 1px solid #e5e5e5;
            }

            .sidebar-header {
                border-bottom: none;
                margin-bottom: 0;
                padding: 10px 10px;
            }

            .session-list {
                flex: 1 1 auto;
                display: flex;
                flex-direction: row;
                overflow-x: auto;
                padding: 0 10px;
            }

            .empty-sessions {
                padding: 0 10px;
                height: 60px;
                flex-direction: row;
                justify-content: flex-start;
            }

            .session-list button {
                min-width: 130px;
                max-width: 200px; /* 可根据需要调整，防止会话按钮太长 */
                width: auto;
            }

            .sidebar .new-session {
                min-width: 120px;
                height: 36px;
                padding: 8px 12px;
                margin: 0 8px 0 0;
            }

            .chat-header, .chat-input-area {
                padding-left: 16px;
                padding-right: 16px;
            }

            .chat-header {
                font-size: 1em;
                padding: 12px 16px;
            }

            .msg-list {
                padding: 20px 16px;
            }
        }

        @media (max-width: 700px) {
            .main-container {
                border-radius: 0;
                box-shadow: none;
            }

            .chat-header, .chat-input-area {
                padding-left: 12px;
                padding-right: 12px;
            }

            .chat-input-area {
                padding: 12px;
            }

            .msg-row {
                margin-bottom: 16px;
            }

            .msg-bubble {
                font-size: 0.95em;
            }

            .sidebar {
                padding: 0;
                max-height: 50px;
                height: 50px;
            }

            .chat-input-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }

            .chat-options {
                width: 100%;
                justify-content: space-between;
            }

            button[type="submit"] {
                width: 100%;
                padding: 10px;
            }
        }

        /*<!-- 添加一些 Markdown 样式 -->*/
        /* Markdown 样式 */
        .markdown-content {
            line-height: 1.6;
            white-space: pre-wrap; /* 保留换行和空格 */
        }

        .markdown-content strong {
            display: inline-block;  /* 让粗体标题单独成行 */
            margin: 0.8em 0 0.4em 0;  /* 添加上下间距 */
            font-weight: 600;
            color: #1a1a1a;
        }

        .markdown-content h1,
        .markdown-content h2,
        .markdown-content h3,
        .markdown-content h4,
        .markdown-content h5,
        .markdown-content h6 {
            margin-top: 24px;
            margin-bottom: 16px;
            font-weight: 600;
            line-height: 1.25;
        }

        .markdown-content pre {
            background: #f6f8fa;
            border-radius: 6px;
            padding: 16px;
            overflow: auto;
            margin: 16px 0;
        }

        .markdown-content code {
            background: #f6f8fa;
            border-radius: 3px;
            padding: 0.2em 0.4em;
            font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;
            font-size: 85%;
        }

        .markdown-content pre code {
            background: none;
            padding: 0;
            white-space: pre;
        }

        .markdown-content h1 {
            font-size: 1.5em;
            padding-bottom: 0.3em;
            border-bottom: 1px solid #eaecef;
        }

        .markdown-content h2 {
            font-size: 1.3em;
            padding-bottom: 0.3em;
            border-bottom: 1px solid #eaecef;
        }

        .markdown-content h3 {
            font-size: 1.1em;
            margin: 1em 0 0.2em 0;  /* 减小上下间距 */
            font-weight: 600;
        }

        .markdown-content p {
            margin: 0.3em 0;  /* 减小段落间距 */
            line-height: 1.8;
        }
        .markdown-content p + h3 {
            margin-top: 1.5em;
        }


        .markdown-content > *:first-child {
            margin-top: 0 !important;
        }

        .markdown-content > *:last-child {
            margin-bottom: 0 !important;
        }

        .markdown-content br {
            display: block;
            content: "";
            margin: 8px 0;
        }

        .markdown-content ul,
        .markdown-content ol {
            margin: 16px 0;
            padding-left: 2em;
        }

        .markdown-content li + li {
            margin-top: 8px;
        }

        .markdown-content li > p {
            margin-top: 16px;
        }
    </style>
</head>
<body>
<div class="main-container">
    <div class="sidebar">
        <div class="sidebar-header">
            <div class="sidebar-title">会话历史</div>
            <button class="clear-all-btn" id="clear-all-btn">清空所有会话</button>
        </div>
        <div class="session-list" id="session-list"></div>
        <button class="new-session" id="new-session-btn">+ 新建会话</button>
    </div>
    <div class="chat-area">
        <div class="chat-header" id="chat-title">AI Chat 示例</div>
        <div class="msg-list" id="msg-history"></div>
        <div class="chat-input-area">
            <form id="chat-form" autocomplete="off">
                <div class="label" style="margin-bottom:2px;">选择预制词/人格：</div>
                <select id="preset-select" style="margin-bottom:4px;">
                    <option value="default">默认（无）</option>
                    <option value="helpful">专业助理（理性、详细、条理清晰）</option>
                    <option value="teenager">中二少年（热血、有趣、口语化）</option>
                    <option value="teacher">耐心老师（善于引导、举例子）</option>
                    <option value="custom">自定义</option>
                </select>
                <textarea id="preset-custom" style="display:none;margin-bottom:2px;"
                          placeholder="请输入自定义预制词..."></textarea>
                <div class="label" style="margin-bottom:2px;">输入你的问题：</div>
                <textarea id="message" required placeholder="请输入内容..."></textarea>
                <div class="chat-input-row">
                    <div class="chat-options">
                        <label for="deepthinking" style="display:flex;align-items:center;">
                            <input type="checkbox" id="deepthinking" checked style="margin-right:5px;">
                            开启深度思考
                        </label>
                    </div>
                    <button type="submit" id="send-btn">发送</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
    // ===== 会话历史管理 =====
    const SESSION_KEY = 'aichat_sessions_v2';
    const SESSION_EXPIRE_KEY = 'aichat_sessions_expire';
    const SESSION_VALID_DAYS = 5;
    let sessions = [];
    let currentSessionId = null;
    let isGenerating = false;

    function uuid() {
        return 'chat-' + Math.random().toString(36).slice(2, 11) + Date.now();
    }

    function getExpireDate(days) {
        return Date.now() + days * 24 * 60 * 60 * 1000;
    }

    function saveSessions() {
        localStorage.setItem(SESSION_KEY, JSON.stringify(sessions));
        localStorage.setItem(SESSION_EXPIRE_KEY, getExpireDate(SESSION_VALID_DAYS));
    }

    function loadSessions() {
        const expire = localStorage.getItem(SESSION_EXPIRE_KEY);
        if (expire && Date.now() > Number(expire)) {
            localStorage.removeItem(SESSION_KEY);
            localStorage.removeItem(SESSION_EXPIRE_KEY);
            return [];
        }
        try {
            return JSON.parse(localStorage.getItem(SESSION_KEY)) || [];
        } catch {
            return [];
        }
    }

    function getSessionById(id) {
        return sessions.find(s => s.id === id);
    }

    function updateSessionName(id, msg) {
        let s = getSessionById(id);
        if (s && msg) {
            s.name = msg.slice(0, 16) + (msg.length > 16 ? '...' : '');
            renderSessionList();
            updateChatTitle();
            saveSessions();
        }
    }

    function updateChatTitle() {
        const titleEl = document.getElementById('chat-title');
        if (currentSessionId) {
            const session = getSessionById(currentSessionId);
            if (session) {
                titleEl.textContent = session.name || 'AI Chat 示例';
                return;
            }
        }
        titleEl.textContent = 'AI Chat 示例';
    }

    function renderSessionList() {
        const list = document.getElementById('session-list');
        list.innerHTML = '';

        if (sessions.length === 0) {
            let emptyDiv = document.createElement('div');
            emptyDiv.className = 'empty-sessions';
            emptyDiv.innerHTML = '无会话记录';
            list.appendChild(emptyDiv);
            return;
        }

        sessions.forEach(s => {
            let btn = document.createElement('button');
            if (s.id === currentSessionId) btn.classList.add('active');

            let titleSpan = document.createElement('span');
            // 强制用 '新会话' 作为默认名，防止空
            titleSpan.textContent = s.name && s.name.trim() ? s.name : '新会话';

            let delBtn = document.createElement('button');
            delBtn.innerHTML = '×';
            delBtn.className = 'session-delete';
            delBtn.onclick = function (e) {
                e.stopPropagation();
                deleteSession(s.id);
            };

            btn.onclick = function () {
                switchSession(s.id);
            };

            btn.appendChild(titleSpan);
            btn.appendChild(delBtn);

            list.appendChild(btn);
        });
    }

    function deleteSession(id) {
        let idx = sessions.findIndex(s => s.id === id);
        if (idx !== -1) {
            sessions.splice(idx, 1);
        }

        if (currentSessionId === id) {
            if (sessions.length > 0) {
                switchSession(sessions[0].id);
            } else {
                currentSessionId = null;
                messages = [];
                renderHistory(true);
                updateChatTitle();
            }
        }

        renderSessionList();
        saveSessions();
    }

    function switchSession(id) {
        let session = getSessionById(id);
        if (!session) return;
        currentSessionId = id;
        renderSessionList();
        messages = session.messages;
        renderHistory(true);
        updateChatTitle();
        scrollToBottom(true);
    }

    function newSession() {
        let id = uuid();
        let s = {
            id,
            name: '新会话',
            created: Date.now(),
            messages: []
        };
        sessions.unshift(s);
        currentSessionId = id;
        renderSessionList();
        messages = s.messages;
        renderHistory(true);
        updateChatTitle();
        scrollToBottom(true);
        saveSessions();
    }

    function clearAllSessions() {
        sessions = [];
        currentSessionId = null;
        messages = [];
        localStorage.removeItem(SESSION_KEY);
        localStorage.removeItem(SESSION_EXPIRE_KEY);
        renderSessionList();
        renderHistory(true);
        updateChatTitle();
    }

    document.getElementById('preset-select').addEventListener('change', function () {
        if (this.value === 'custom') {
            document.getElementById('preset-custom').style.display = 'block';
        } else {
            document.getElementById('preset-custom').style.display = 'none';
        }
    });
    let messages = [];

    function renderHistory(scrollToEnd) {
        // 配置 marked
        marked.setOptions({
            breaks: true,  // 支持换行
            gfm: true,     // 启用GitHub风格Markdown
            headerIds: false,
            mangle: false,
            highlight: function (code, lang) {
                // 如果要添加代码高亮，可以在这里集成Prism.js或Highlight.js
                return code;
            }
        });

        function preprocessContent(content) {
            return content
                // 主标题（比如 "Java的主要特点："）作为独立段落
                .replace(/(Java的[\u4e00-\u9fa5]+：)/g, '$1\n')
                // 数字标题（比如 "1.跨平台性："）和它的内容作为一个段落
                .replace(/\s*(\d+\.[\u4e00-\u9fa5]+：)[^\n]*/g, '\n$&')
                // 其他标题（比如 "自动内存管理："）和它的内容作为一个段落
                .replace(/\s*([\u4e00-\u9fa5]+：)[^\n]*/g, '\n$&')
                // 清理开头的换行
                .replace(/^\n+/, '')
                // 清理连续的换行
                .replace(/\n\s*\n/g, '\n');
        }

        const msgList = document.getElementById('msg-history');
        msgList.innerHTML = '';

        // 如果没有消息，显示空状态
        if (messages.length === 0) {
            msgList.classList.add('empty');
            let emptyDiv = document.createElement('div');
            emptyDiv.className = 'empty-chat-message';
            emptyDiv.innerHTML = '开始新的对话<br>输入问题并发送';
            msgList.appendChild(emptyDiv);
            return;
        }

        // 有消息时移除空状态
        msgList.classList.remove('empty');

        messages.forEach((msg, idx) => {
            if (msg.role === 'user') {
                let row = document.createElement('div');
                row.className = 'msg-row user';
                // 先用 marked 解析，再进行 HTML 转义
                const parsedContent = marked.parse(msg.content).replace(/---###/g, '\n').replace(/###/g, '\n');
                // 从这里
                row.innerHTML = `
    <div class="msg-content">
        <div class="msg-bubble user markdown-content">${marked.parse(escapeHTML(msg.content))}</div>
        <div class="msg-meta"></div>
    </div>
    <div class="msg-avatar user">U</div>`;
                msgList.appendChild(row);
            } else // 在 renderHistory 函数中，修改 AI 回复的渲染部分
            if (msg.role === 'assistant') {
                let row = document.createElement('div');
                row.className = 'msg-row ai';
                let reasoning = msg.reasoning || '';
                const hasReasoning = reasoning && reasoning.trim() !== '';
                let reasoningHtml = '';
                if (hasReasoning) {
                    const isCollapsed = msg.reasoningHide === true;
                    const processedReasoning = preprocessContent(reasoning);
                    const parsedReasoning = marked.parse(processedReasoning).replace(/---###/g, '\n').replace(/###/g, '\n');
                    reasoningHtml = `
        <div class="reasoning-container ${isCollapsed ? 'collapsed' : ''}" data-idx="${idx}">
            <div class="reasoning-header" onclick="toggleReasoning(${idx})">
                <span>思考过程</span>
                <span>${isCollapsed ? '显示' : '隐藏'}</span>
            </div>
            <div class="reasoning-content markdown-content">${parsedReasoning}</div>
        </div>`;
                }

                const processedContent = preprocessContent(msg.content);
                row.innerHTML = `
    <div class="msg-avatar ai">AI</div>
    <div class="msg-content">
        ${reasoningHtml}
        <div class="msg-bubble ai">
            <div class="ai-reply-content markdown-content">${marked.parse(escapeHTML(processedContent))}</div>
        </div>
        <div class="msg-meta"></div>
    </div>`;
                msgList.appendChild(row);
            }
        });
        if (scrollToEnd) scrollToBottom(true);
    }

    function toggleReasoning(idx) {
        const container = document.querySelector(`.reasoning-container[data-idx="${idx}"]`);
        if (container) {
            const isCollapsed = container.classList.contains('collapsed');
            container.classList.toggle('collapsed');
            const header = container.querySelector('.reasoning-header');
            if (header) {
                header.querySelector('span:last-child').textContent = isCollapsed ? '隐藏' : '显示';
            }
            messages[idx].reasoningHide = !isCollapsed;
            saveSessions();
        }
    }

    window.toggleReasoning = toggleReasoning;

    function shouldAutoScroll() {
        const msgListDiv = document.getElementById('msg-history');
        return msgListDiv.scrollHeight - msgListDiv.scrollTop - msgListDiv.clientHeight < 120;
    }

    function scrollToBottom(force) {
        setTimeout(() => {
            let msgListDiv = document.getElementById('msg-history');
            if (force || shouldAutoScroll()) {
                msgListDiv.scrollTop = msgListDiv.scrollHeight;
            }
        }, 20);
    }

    document.getElementById('chat-form').addEventListener('submit', async function (e) {
        e.preventDefault();
        if (!isGenerating) {
            sendMessage();
        }
    });
    document.getElementById('message').addEventListener('keydown', function (e) {
        if (e.key === "Enter" && !e.shiftKey) {
            e.preventDefault();
            if (!isGenerating) {
                sendMessage();
            }
        }
    });

    async function sendMessage() {
        let msg = document.getElementById('message').value.trim();
        if (!msg) return;

        isGenerating = true;
        document.getElementById('send-btn').disabled = true;

        let deepthink = document.getElementById('deepthinking').checked;
        let presetType = document.getElementById('preset-select').value;
        let preset = '';
        if (presetType === "default") {
            preset = '';
        } else if (presetType === "helpful") {
            preset = '你现在是一个专业的AI助理，回答要详细、理性、条理清晰、善于总结。';
        } else if (presetType === "teenager") {
            preset = '请用中二热血少年风格回复，语言口语化，有趣又不失逻辑。';
        } else if (presetType === "teacher") {
            preset = '你现在是一位耐心的老师，习惯用举例和类比引导学生理解知识。';
        } else if (presetType === "custom") {
            preset = document.getElementById('preset-custom').value.trim();
        }

        // 如果没有当前会话，创建一个新会话
        if (!currentSessionId) newSession();

        // 判断是否是第一次提问
        const isFirstMessage = messages.length === 0;

        // 添加用户消息
        messages.push({role: 'user', content: msg});

        // 如果是第一次提问，用消息内容更新会话名称
        if (isFirstMessage) {
            updateSessionName(currentSessionId, msg);
        }

        renderHistory(true);
        scrollToBottom(true);
        document.getElementById('message').value = '';

        // 在第一条消息发送后，立即设置会话标题
        if (isFirstMessage) {
            let session = getSessionById(currentSessionId);
            if (session) {
                session.name = msg.slice(0, 16) + (msg.length > 16 ? '...' : '');
                updateChatTitle();
                renderSessionList(); // 重新渲染会话列表以显示新标题
            }
        }

        saveSessions();

        // 添加AI的空白消息占位
        messages.push({role: 'assistant', content: '', reasoning: '', reasoningHide: false});
        renderHistory(true);
        scrollToBottom(true);

        // ========== 增量渲染流式 ==========
        const response = await fetch('/api/chat/stream', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                messages: messages.slice(0, messages.length - 1),
                deepthinking: deepthink,
                preset: preset
            })
        });
        const decoder = new TextDecoder('utf-8');
        const reader = response.body.getReader();
        let buffer = "";
        let aiReply = "";
        let aiReasoning = "";
        let lastIdx = messages.length - 1;

        // 获取聊天容器和相关元素
        let msgListDiv = document.getElementById('msg-history');
        let aiRows = msgListDiv.querySelectorAll('.msg-row.ai');
        let lastAiRow = aiRows[aiRows.length - 1];
        let reasoningContainer = null;
        let reasoningContent = null;
        let replyContent = null;

        if (lastAiRow) {
            reasoningContainer = lastAiRow.querySelector('.reasoning-container');
            if (!reasoningContainer && deepthink) {
                // 如果开启了深度思考但没有推理容器，创建一个
                const msgContent = lastAiRow.querySelector('.msg-content');
                reasoningContainer = document.createElement('div');
                reasoningContainer.className = 'reasoning-container';
                reasoningContainer.dataset.idx = lastIdx;
                reasoningContainer.innerHTML = `
                    <div class="reasoning-header" onclick="toggleReasoning(${lastIdx})">
                        <span>思考过程</span>
                        <span>隐藏</span>
                    </div>
                    <div class="reasoning-content"></div>
                `;

                // 插入到消息内容的开头
                if (msgContent.firstChild) {
                    msgContent.insertBefore(reasoningContainer, msgContent.firstChild);
                } else {
                    msgContent.appendChild(reasoningContainer);
                }
            }

            if (reasoningContainer) {
                reasoningContent = reasoningContainer.querySelector('.reasoning-content');
            }

            replyContent = lastAiRow.querySelector('.ai-reply-content');
        }

        while (true) {
            const {done, value} = await reader.read();
            if (done) break;
            buffer += decoder.decode(value, {stream: true});
            let events = buffer.split('\n\n');
            buffer = events.pop();

            for (const event of events) {
                if (event.indexOf('event:') === 0) {
                    let lines = event.split('\n');
                    let eventType = '';
                    let eventData = '';

                    lines.forEach(line => {
                        if (line.startsWith('event:')) eventType = line.replace('event:', '').trim();
                        if (line.startsWith('data:')) eventData += line.replace('data:', '').trim();
                    });

                    if (eventType === 'reasoning' && deepthink) {
                        let delta = eventData;
                        if (delta.length > 0) {
                            aiReasoning += delta;
                            messages[lastIdx].reasoning = aiReasoning;

                            if (reasoningContent) {
                                // 先用 marked 解析，再处理特殊字符
                                const parsedReasoning = marked.parse(aiReasoning).replace(/---###/g, '\n').replace(/###/g, '\n');
                                reasoningContent.innerHTML = parsedReasoning;
                            }
                        }
                        scrollToBottom();
                        saveSessions();
                    }

                    if (eventType === 'reply') {
                        let delta = eventData;
                        if (delta.length > 0) {
                            aiReply += delta;
                            messages[lastIdx].content = aiReply;

                            if (replyContent) {
                                // 先用 marked 解析，再处理特殊字符
                                const parsedReply = marked.parse(aiReply).replace(/---###/g, '\n').replace(/###/g, '\n');
                                replyContent.innerHTML = parsedReply;
                            }
                        }
                        scrollToBottom();
                        saveSessions();
                    }
                }
            }
        }

        // 更新最终内容
        messages[lastIdx].content = aiReply;
        messages[lastIdx].reasoning = aiReasoning;

        // 结束生成，重新启用发送按钮
        isGenerating = false;
        document.getElementById('send-btn').disabled = false;

        saveSessions();
    }

    function escapeHTML(str) {
        if (!str) return '';
        // 只转义 < > " ' 字符，保留其他 Markdown 字符
        return str.replace(/[<>"']/g, function (c) {
            return {
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#39;'
            }[c];
        });
    }

    function initApp() {
        sessions = loadSessions();
        if (sessions.length > 0) {
            currentSessionId = sessions[0].id;
            messages = getSessionById(currentSessionId).messages;
        } else {
            currentSessionId = null;
            messages = [];
        }
        renderSessionList();
        renderHistory(true);
        updateChatTitle();
    }

    document.getElementById('new-session-btn').onclick = function () {
        newSession();
        saveSessions();
    };
    document.getElementById('clear-all-btn').onclick = clearAllSessions;
    window.onload = function () {
        initApp();
        document.getElementById('message').focus();
    };
</script>
</body>
</html>